<?php

class EpalProductHolder extends Page{
    private static $db = array();
    private static $has_one = array(
        'ECategory' => 'ECategory'
    );
    static $allowed_children = array("EpalProductHolder");

    public function getCMSFields(){
        $fields = parent::getCMSFields();
        $fields->removeByName('Content');

        $arrCategory = ECategory::get()->map('ID', 'Title')->toArray();
        asort($arrCategory);
        $categoryField = new DropdownField('ECategoryID', 'Category', $arrCategory);
        $categoryField->setEmptyString('Select one');

        $fields->addFieldToTab('Root.Main', $categoryField, 'Metadata');

        $productConfig = GridFieldConfig_RecordEditor::create()->addComponent(new GridFieldSortableRows('SortOrder'));
        $productConfig->removeComponentsByType('GridFieldAddNewButton');
        $productConfig->removeComponentsByType('GridFieldDeleteAction');
//        $productConfig->removeComponentsByType('GridFieldEditButton');

        $productGridField = new GridField(
            'EProduct',
            'EProduct',
            EProduct::get()->leftJoin('EProduct_ECategories', "EProduct.ID = EProduct_ECategories.EProductID")->filter(array('ECategoryID' => $this->ECategory()->ID)),
            $productConfig
        );
        $fields->findOrMakeTab('Root.ProductsTab', 'Products');
        $fields->addFieldToTab('Root.ProductsTab', $productGridField);


        return $fields;
    }

    function getCurrentProductTitle(){
        return Session::get('EProductDetailTitle');
    }

}

class EpalProductHolder_Controller extends Page_Controller{
    static $allowed_actions = array(
        'sp'
    );

    public function sp(){
        $paramID = $this->request->param('ID');
        $productUrlSegment = SiteTree::create()->generateURLSegment($paramID);
        $product = EProduct::get()->filter(array('UrlSegment' => $productUrlSegment))->first();
        if($product){
            Session::set('EProductDetailTitle', $product->Title);
            return $this->customise(array('Product' => $product))->renderWith(array('EProductDetailPage', 'Page'));
        }
        return $this->redirectBack();
    }

    public function PaginatedProductByCategory() {
        $paginatedList = new PaginatedList($this->ECategory()->EProducts(), $this->request);
        $paginatedList->setPageLength(12);
        return $paginatedList;
    }

    function getCurrentProduct(){
        $paramID = $this->request->param('ID');
        $productUrlSegment = SiteTree::create()->generateURLSegment($paramID);

        return EProduct::get()->filter(array('UrlSegment' => $productUrlSegment))->first();
    }

}